package com.ruoyi.web.controller.cems;

import com.ruoyi.cems.domain.BmsEVCContact;
import com.ruoyi.cems.domain.BmsEmergencyNotice;
import com.ruoyi.cems.domain.BmsEmergencyVariableControl;
import com.ruoyi.cems.domain.BmsWorkChecklists;
import com.ruoyi.cems.domain.dto.BmsEVCContactResponse;
import com.ruoyi.cems.domain.dto.BmsEmergencyVariableControlDTO;
import com.ruoyi.cems.domain.dto.BmsEmergencyVariableControlResponse;
import com.ruoyi.cems.service.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 变量控制;Controller
 * 
 * @author ruoyi
 * @date 2024-06-24
 */
@Api(description="变量控制管理")
@RestController
@RequestMapping("/cems/control")
public class BmsEmergencyVariableControlController extends BaseController
{
    @Autowired
    private IBmsEmergencyVariableControlService bmsEmergencyVariableControlService;
    @Autowired
    private IBmsEVCContactService  bmsEVCContactService;
    @Autowired
    private IBmsEvcBelongOfficeContactService bmsEvcBelongOfficeContactService;
    @Autowired
    private IBmsEvcAlternateAirportService bmsEvcAlternateAirportService;
    @Autowired
    private IBmsEmergencyNoticeService bmsEmergencyNoticeService;
    @Autowired
    private IBmsWorkChecklistsService bmsWorkChecklistsService;

    @Value("${evc.template.message}")
    private String messageTemplate;

    /**
     * 查询变量控制;列表
     */
    @ApiOperation("查询变量控制")
    @GetMapping("/list")
    public TableDataInfo list(BmsEmergencyVariableControlDTO bevcDto)
    {
        startPage();
        if(!SecurityUtils.hasRole("manager")){
            //数据权限:普通用户：仅自己
            bevcDto.setManager(false);
            bevcDto.setUserId(getUserId().toString());
        }else {
            bevcDto.setManager(true);
        }
        bevcDto.setUnitCode(getLoginUser().getUser().getUnit());
        List<BmsEmergencyVariableControl> list = bmsEmergencyVariableControlService.selectBmsEmergencyVariableControlList(bevcDto);
        return getDataTable(list);
    }

    /**
     * 导出变量控制;列表
     */
    @ApiOperation("导出变量控制")
    @Log(title = "变量控制", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BmsEmergencyVariableControlDTO bevcDto)
    {
        bevcDto.setUnitCode(getLoginUser().getUser().getUnit());
        List<BmsEmergencyVariableControl> list = bmsEmergencyVariableControlService.selectBmsEmergencyVariableControlList(bevcDto);
        ExcelUtil<BmsEmergencyVariableControl> util = new ExcelUtil<BmsEmergencyVariableControl>(BmsEmergencyVariableControl.class);
        util.exportExcel(response, list, "变量控制的数据");
    }

    /**
     * 获取变量控制;详细信息
     */
    @ApiOperation("获取变量控制")
    @GetMapping(value = { "/{id}" })
    public AjaxResult getInfo(@PathVariable(value="id",required = false) String id)
    {
        BmsEmergencyVariableControl bvc= bmsEmergencyVariableControlService.selectBmsEmergencyVariableControlByID(id);
        bvc.setEvcContacts(bmsEVCContactService.selectBmsEVCContactListByparentId(id,null));
        bvc.setEvcBelongOfficeContacts(bmsEvcBelongOfficeContactService.selectBmsEvcBelongOfficeContactListByVcId(id));
        bvc.setEvcAlternateAirports(bmsEvcAlternateAirportService.selectBmsEvcAlternateAirportListByVcId(id));
        BmsEVCContact evcContact = new BmsEVCContact();
        evcContact.setUserId(getUserId().toString());
        evcContact.setType("command");
        evcContact.setParentId(bvc.getID());
        List<BmsEVCContact> evcContactList = bmsEVCContactService.selectBmsEVCContactList(evcContact);
        if(Objects.nonNull(evcContactList) && !evcContactList.isEmpty()){
            evcContactList.forEach(bmsEVCContact -> {
                if(Objects.isNull(bmsEVCContact.getViewTime())){
                    bmsEVCContact.setViewTime(new Date());
                    bmsEVCContactService.updateBmsEVCContact(bmsEVCContact);
                }
            });
        }
        return success(bvc);
    }
    /**
     * 获取变量控制;详细信息
     */
    @ApiOperation("获取变量控制")
    @GetMapping(value = { "/getInfoByTaskNo" })
    public AjaxResult getInfoByTaskNo(@RequestParam(value="taskNo",required = true) String taskNo)
    {
        BmsEmergencyVariableControlResponse response = new BmsEmergencyVariableControlResponse();
        BmsEmergencyVariableControl bvc= bmsEmergencyVariableControlService.selectBmsEmergencyVariableControlByTaskNo(taskNo);
        Map<String, BmsWorkChecklists>workChecklistsMap  = new HashMap<>();
        //获取最新一条应急通知单
        BmsEmergencyNotice bmsEmergencyNotice = new BmsEmergencyNotice();
        bmsEmergencyNotice.setVcId(bvc.getID());
        bmsEmergencyNotice.setStatus("StartUp");
        bmsEmergencyNotice.setManager(true);
        List<BmsEmergencyNotice> bmsEmergencyNotices = bmsEmergencyNoticeService.selectBmsEmergencyNoticeList(bmsEmergencyNotice);
        if(Objects.nonNull(bmsEmergencyNotices) && !bmsEmergencyNotices.isEmpty()){
            bmsEmergencyNotice = bmsEmergencyNotices.get(0);
            //赋值给Response
            response.setTaskNo(bmsEmergencyNotice.getTaskNo());
            response.setAirport(bmsEmergencyNotice.getAirport());
            response.setCantry(bmsEmergencyNotice.getCantry());
            response.setView(bmsEmergencyNotice.getView());
            response.setResponseLevel(bmsEmergencyNotice.getResponseLevel());
            response.setActionLevel(bmsEmergencyNotice.getActionLevel());
            String message = String.format(messageTemplate, bmsEmergencyNotice.getAirport(),bmsEmergencyNotice.getCantry(),bmsEmergencyNotice.getView(),bmsEmergencyNotice.getResponseLevel(),bmsEmergencyNotice.getTaksContent());
            response.setMessage(message);
            List<BmsWorkChecklists> bmsWorkChecklists = bmsWorkChecklistsService.selectBmsWorkChecklistsByEnID(bmsEmergencyNotice.getID());
            if(Objects.nonNull(bmsWorkChecklists) && !bmsWorkChecklists.isEmpty()){
                bmsWorkChecklists.forEach(bmsWorkChecklist -> {
                    workChecklistsMap.put(bmsWorkChecklist.getJobNumber(), bmsWorkChecklist);
                });
            }
        }
        //联络人信息
        List<BmsEVCContact> bmsEVCContacts = bmsEVCContactService.selectBmsEVCContactListByparentId(bvc.getID(),null);
        List<BmsEVCContactResponse> bmsEVCContactResponses = new ArrayList<>();
        if(Objects.nonNull(bmsEVCContacts) && !bmsEVCContacts.isEmpty()){
            for (BmsEVCContact bmsEVCContact : bmsEVCContacts) {
                BmsEVCContactResponse bmsEVCContactResponse = new BmsEVCContactResponse();
                bmsEVCContactResponse.setName(bmsEVCContact.getName());
                bmsEVCContactResponse.setTel(bmsEVCContact.getTel());
                bmsEVCContactResponse.setRoleName(bmsEVCContact.getRoleName());
                bmsEVCContactResponse.setDuty(bmsEVCContact.getDuty());
                if(workChecklistsMap.containsKey(bmsEVCContact.getJobNumber())){
                    bmsEVCContactResponse.setDuty(workChecklistsMap.get(bmsEVCContact.getJobNumber()).getDuty());
                }

                bmsEVCContactResponses.add(bmsEVCContactResponse);
            }
            response.setEvcContacts(bmsEVCContactResponses);
        }
        return success(response);
    }

    /**
     * 新增变量控制;
     */
    @ApiOperation("新增变量控制")
    @Log(title = "变量控制", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BmsEmergencyVariableControl bmsEmergencyVariableControl)
    {
        bmsEmergencyVariableControl.setID(UUID.randomUUID().toString().replace("-", ""));
        bmsEmergencyVariableControl.setCreatedBy(getUserId().toString());
        bmsEmergencyVariableControl.setCreatedTime(new Date());
        bmsEmergencyVariableControl.setStatus("1");
        bmsEmergencyVariableControl.setUnitCode(getLoginUser().getUser().getUnit());
        return toAjax(bmsEmergencyVariableControlService.insertBmsEmergencyVariableControl(bmsEmergencyVariableControl));
    }
    /**
     * 发布变量控制
     */
    @ApiOperation(value = "发布变量控制")
    @Log(title = "发布变量控制", businessType = BusinessType.OTHER)
    @PostMapping("/start")
    public AjaxResult start(@RequestBody BmsEmergencyVariableControl bmsEmergencyVariableControl)
    {
        return toAjax(bmsEmergencyVariableControlService.start(bmsEmergencyVariableControl, getUserId().toString()));
    }

    /**
     * 修改变量控制;
     */
    @ApiOperation("修改变量控制")
    @Log(title = "变量控制", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BmsEmergencyVariableControl bmsEmergencyVariableControl)
    {
        bmsEmergencyVariableControl.setUpdatedBy(getUserId().toString());
        bmsEmergencyVariableControl.setUpdatedTime(new Date());
        return toAjax(bmsEmergencyVariableControlService.updateBmsEmergencyVariableControl(bmsEmergencyVariableControl));
    }

    /**
     * 删除变量控制;
     */
    @ApiOperation("删除变量控制")
    @Log(title = "变量控制", businessType = BusinessType.DELETE)
	@DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable String[] IDs)
    {
        return toAjax(bmsEmergencyVariableControlService.deleteBmsEmergencyVariableControlByIDs(IDs));
    }

    /**
     *复制变量控制表
     */
    @ApiOperation(value = "复制变量控制")
    @Log(title = "复制变量控制",businessType = BusinessType.OTHER)
    @PostMapping("/copy")
    public AjaxResult copy(@RequestBody BmsEmergencyVariableControl bmsEmergencyVariableControl){
        return toAjax(bmsEmergencyVariableControlService.copy(bmsEmergencyVariableControl.getID(),getUserId().toString()));
    }
}
